using ColorFillGame.Domain.Exceptions;
using ColorFillGame.Domain.Repositories;
using ColorFillGame.Domain.Services;
using MediatR;

namespace ColorFillGame.Application.Commands.Game;

public class LeaveGameCommandHandler : IRequestHandler<LeaveGameCommand>
{
    private readonly IGameRepository _gameRepository;
    private readonly IPlayerRepository _playerRepository;
    private readonly IGameService _gameService;

    public LeaveGameCommandHandler(
        IGameRepository gameRepository,
        IPlayerRepository playerRepository,
        IGameService gameService)
    {
        _gameRepository = gameRepository;
        _playerRepository = playerRepository;
        _gameService = gameService;
    }

    public async Task Handle(LeaveGameCommand request, CancellationToken cancellationToken)
    {
        // 获取游戏
        var game = await _gameRepository.GetByIdAsync(request.GameId);
        if (game == null)
            throw new GameNotFoundException(request.GameId);

        // 获取玩家
        var player = await _playerRepository.GetByIdAsync(request.PlayerId);
        if (player == null)
            throw new PlayerNotFoundException(request.PlayerId);

        // 检查玩家是否属于该游戏
        if (player.GameId != request.GameId)
            throw new DomainException("Player does not belong to this game.");

        // 从游戏中移除玩家
        _gameService.LeaveGame(game, request.PlayerId);
        await _gameRepository.UpdateAsync(game);
        await _gameRepository.SaveChangesAsync();

        // 删除玩家
        await _playerRepository.DeleteAsync(request.PlayerId);
        await _playerRepository.SaveChangesAsync();
    }
}